package com.wang.jmonkey.interceptor.config;

import cn.hutool.core.collection.CollUtil;
import com.wang.jmonkey.common.result.HttpResult;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Description Controller 全局异常处理
 * @Author HeJiawang
 * @Date 2021/5/27 14:41
 */
@Configuration
@RestControllerAdvice
public class ControllerExceptionHandlerAutoConfig {

    /**
     * 参数校验错误处理
     * @param e 错误信息
     * @return http result
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public HttpResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        HttpResult<Void> result = new HttpResult<Void>().error("参数校验错误");

        List<ObjectError> allErrorList = e.getBindingResult().getAllErrors();
        if (CollUtil.isNotEmpty(allErrorList)) {
            result.setMsg(allErrorList.get(0).getDefaultMessage());
        }

        return result;
    }

    /**
     * 参数绑定错误处理
     * @param e 参数绑定异常
     * @return 错误信息处理
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public HttpResult<Void> handleBindException(BindException e) {
        HttpResult<Void> result = new HttpResult<Void>().error("参数绑定错误");

        List<ObjectError> allErrorList = e.getBindingResult().getAllErrors();
        if (CollUtil.isNotEmpty(allErrorList)) {
            result.setMsg(allErrorList.get(0).getDefaultMessage());
        }

        return result;
    }
}
